using System;
using Microsoft.SPOT;
using Gadgeteer;
using Microsoft.SPOT.Hardware;
using Gadgeteer.Modules;

namespace MLRobotic.Asserv.Drivers
{
    public class SpiHub : Module
    {
        private Socket sSocket;
        private Socket sx1;
        private Socket sx2;

        /// <summary>
        /// Returns the socket number for socket 1 on the hub.
        /// 
        /// </summary>
        public int SHubSocket1
        {
            get { return this.sx1.SocketNumber; }
        }

        /// <summary>
        /// Returns the socket number for socket 2 on the hub.
        /// 
        /// </summary>
        public int SHubSocket2
        {
            get { return this.sx2.SocketNumber; }
        }

        /// <summary>
        /// Creates a new SPlus instance.
        /// </summary>
        /// <param name="socketNumber">The socket that this module is plugged in to.
        public SpiHub(int socketNumber)
        {
            this.sSocket = Socket.GetSocket(socketNumber, true, (Module) this, (string) null);
            this.sSocket.EnsureTypeIsSupported('S', (Module) this);

            this.sx1 = Socket.SocketInterfaces.CreateUnnumberedSocket("SpiHub1");
            this.sx2 = Socket.SocketInterfaces.CreateUnnumberedSocket("SpiHub2");

            Socket socket1 = this.sx1;
            Socket socket2 = this.sx2;
            socket1.SupportedTypes = new char[1] { 'S' };
            socket2.SupportedTypes = new char[1] { 'S' };

            this.sx1.CpuPins[3] = this.sx2.CpuPins[3] = (Cpu.Pin)(int)this.sSocket.CpuPins[3];
            this.sx1.CpuPins[4] = this.sx2.CpuPins[4] = (Cpu.Pin)(int)this.sSocket.CpuPins[4];
            this.sx2.CpuPins[6] = (Cpu.Pin)(int)this.sSocket.CpuPins[5];
            this.sx1.CpuPins[6] = (Cpu.Pin)(int)this.sSocket.CpuPins[6];

            this.sx1.CpuPins[7] = this.sx2.CpuPins[7] = (Cpu.Pin) (int) this.sSocket.CpuPins[7];
            this.sx1.CpuPins[8] = this.sx2.CpuPins[8] = (Cpu.Pin) (int) this.sSocket.CpuPins[8];
            this.sx1.CpuPins[9] = this.sx2.CpuPins[9] = (Cpu.Pin) (int) this.sSocket.CpuPins[9];

            this.sx1.SPIModule = this.sx2.SPIModule = this.sSocket.SPIModule;

            Socket.SocketInterfaces.RegisterSocket(this.sx1);
            Socket.SocketInterfaces.RegisterSocket(this.sx2);
        }
    }
}
